package com.legsem.jhosync.ws.rs;

import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status.Family;
import javax.ws.rs.core.Response.StatusType;

import com.legsem.jhosync.AuthenticationException;
import com.legsem.jhosync.Server;
import com.legsem.jhosync.ServerException;
import com.legsem.jhosync.dto.ApiParms;

/**
 * The server is programmable using a REST API.
 * 
 */
@Path("api")
public class ApiResource extends AbstractResource {

    @Path("get_api_token")
    @POST
    @Consumes("application/json")
    @Produces(MediaType.TEXT_PLAIN)
    public Response getApiToken(InputStream apiParmsStream,
            @Context HttpServletRequest req) {
        try {
            Server server = getServer(req);
            return Response.ok(server.doApiGetToken()).build();

        } catch (ServerException e) {
            return Response.status(new StatusType() {

                public int getStatusCode() {
                    return 422;
                }

                public Family getFamily() {
                    return Family.CLIENT_ERROR;
                }

                public String getReasonPhrase() {
                    return "Invalid/missing API user";
                }
            }).build();
        } catch (Exception e) {
            throw new WebApplicationException(e,
                    Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @Path("reset")
    @POST
    @Consumes("application/json")
    @Produces(MediaType.TEXT_PLAIN)
    public Response reset(InputStream apiParmsStream,
            @Context HttpServletRequest req) {
        try {
            ApiParms apiParms = getMapper().readValue(apiParmsStream,
                    ApiParms.class);
            Server server = getServer(req);
            return Response.ok(server.doApiReset(apiParms)).build();

        } catch (final AuthenticationException e) {
            return Response.status(new StatusType() {

                public int getStatusCode() {
                    return 422;
                }

                public Family getFamily() {
                    return Family.CLIENT_ERROR;
                }

                public String getReasonPhrase() {
                    return e.getMessage();
                }
            }).build();
        } catch (Exception e) {
            throw new WebApplicationException(e,
                    Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
}
